//
//  LKOpenShopStepFiveViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/6/9.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKOpenShopStepFiveViewController.h"
#import "LKUFPictureRow.h"
#import "LKUFPictureRowCell.h"
#import "LKUFOpenShopHeaderRow.h"
#import "LKUFOpenShopHeaderRowCell.h"
#import "LKUFOpenShopBottomButtonRow.h"
#import "LKUFOpenShopBottomButtonRowCell.h"
#import "LKBankListViewController.h"
#import "LKManagerAllianceViewController.h"
@interface LKOpenShopStepFiveViewController (){
    dispatch_group_t _group;
    dispatch_queue_t _queue;
    dispatch_semaphore_t semaphore;
}

@property(nonatomic,strong)UFFormView *formview;
@property(nonatomic,assign)NSInteger pictureTapSelectIndex;
@property(nonatomic,strong)UIImage *selcetedUploadImage;

@end

@implementation LKOpenShopStepFiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"商户开通";
    _group = dispatch_group_create();
    _queue = dispatch_queue_create("seriersQueue", DISPATCH_QUEUE_SERIAL);
      semaphore  = dispatch_semaphore_create(1);
    [self setNavgationRightBtn];
    [self createFormView];
    // Do any additional setup after loading the view.
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"暂存" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        weakSelf.inforModel.status = @"6";
        NSDictionary *param = [self.inforModel properties_aps];
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopOpenInformationEditUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
           [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
/// 创建表单的view
/*****************************创建法人账号*******************************/
-(void)createFormView{
    WS(weakSelf)
    self.formview = [UFFormView makeFormView:^(UFFormViewMaker * _Nonnull make) {
        make
        .registerRow([LKUFOpenShopHeaderRow class], [LKUFOpenShopHeaderRowCell class])
        .registerRow([LKUFPictureRow class], [LKUFPictureRowCell class])
        .registerRow([LKUFOpenShopBottomButtonRow class], [LKUFOpenShopBottomButtonRowCell class])
        .addSection([UFSection makeSection:^(UFSectionMaker * _Nonnull make) {
            make
            .titleStyle([UFRowTitleStyle makeTitleStyle:^(UFRowTitleStyleMaker * _Nonnull make) {
               make
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor)
                .textAlignment(NSTextAlignmentLeft);
            }])
            .valueStyle([UFTextStyle makeTextStyle:^(UFRowTextStyleMaker * _Nonnull make) {
                make
                .textAlignment(NSTextAlignmentRight)
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor);
            }])
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFOpenShopHeaderRow *row = [[LKUFOpenShopHeaderRow alloc] init];
                row.headerImage = [UIImage imageNamed:@"编组 8"];
                row.height = (WIDTH - 26)/7 + 20;
                return row;
            })
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFPictureRow *pictureRow = [[LKUFPictureRow alloc] init];
                pictureRow.pictureNumbers = 2;
                pictureRow.headerTitle = @"银行卡照片";
                pictureRow.titlesPlaceArray = @[@"银行卡正面照片",@"银行卡背面照片"];
                pictureRow.picturesArray = [[NSMutableArray alloc] initWithArray:@[weakSelf.inforModel.positive_bank_card_img,weakSelf.inforModel.bank_card_img]];
                pictureRow.height = 145;
                pictureRow.uploadImageBlock = ^(NSInteger selectValue, UIImageView * _Nonnull selecteImageV) {
                    dispatch_group_notify(self->_group, dispatch_get_main_queue(), ^{
                        dispatch_semaphore_signal(self->semaphore);
                        weakSelf.pictureTapSelectIndex = 1;
                        [weakSelf showAlertChooseVc];
                    });
                };
                return pictureRow;
            })
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .editable(NO)
                .height(RowHeightDefault)
                .title(@"开户人")
                .name(@"开户人")
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.uni_name = value;
                })
                .value(weakSelf.inforModel.uni_name);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .editable(NO)
                  .title(@"开户银行")
                  .name(@"开户银行")
                
                  .value(weakSelf.inforModel.bank_account)
                  .rowDidSelected(^(__kindof UFRow * _Nonnull row) {
                      LKBankListViewController *bank = [[LKBankListViewController alloc] init];
                      bank.isBankAccount = YES;
                      bank.bankBlock = ^(NSString * _Nullable bank, NSString * _Nullable bank_num) {
                          weakSelf.inforModel.bank_account = bank;
                          weakSelf.inforModel.bank_num = bank_num;
                        weakSelf.inforModel.branch_account = @"";
                          [weakSelf.formview removeFromSuperview];
                          [weakSelf createFormView];
                      };
//                      bank.bankBlock = ^(NSString * _Nullable bank, NSString * _Nullable bank_num) {
//                          weakSelf.inforModel.bank_account = bank;
//                          weakSelf.inforModel.bank_num = bankNumber;
//                          [weakSelf.formview removeFromSuperview];
//                          [weakSelf createFormView];
//                      };
                      [weakSelf.navigationController pushViewController:bank animated:YES];
                  })
                  .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {

                  })
                  .height(RowHeightDefault)
                  .accessoryType(UFRowAccessoryDisclosureIndicator);
            }])
            .addRow([UFAreaPickerRow makeAreaPickerRow:^(UFAreaPickerRowMaker * _Nonnull make) {
                make
                .areaSeparator(@",")
                .title(@"开户省市")
                .name(@"address")
                .value([NSString stringWithFormat:@"%@%@%@",weakSelf.inforModel.province_area,weakSelf.inforModel.city_area,weakSelf.inforModel.county_area])
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.branch_account = @"";
                    NSArray *addressArray = [value componentsSeparatedByString:@","];
                    if (addressArray.count == 3) {
                        weakSelf.inforModel.province_area = addressArray[0];
                        weakSelf.inforModel.city_area = addressArray[1];
                        weakSelf.inforModel.county_area = addressArray[2];
                    }else{
                        weakSelf.inforModel.province_area = addressArray[0];
                        weakSelf.inforModel.county_area = addressArray[1];
                    weakSelf.inforModel.city_area = [weakSelf.inforModel.province_area mutableCopy];
                    weakSelf.inforModel.province_area = [[weakSelf.inforModel.province_area componentsSeparatedByString:@"市"] firstObject];
                    }

                })
                .accessoryType(UFRowAccessoryDisclosureIndicator);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                 make
                  .editable(NO)
                  .title(@"开户支行")
                  .name(@"开户支行")
                  .value(weakSelf.inforModel.branch_account)
                  .rowDidSelected(^(__kindof UFRow * _Nonnull row) {
                      if (weakSelf.inforModel.bank_account.length == 0) {
                          [SVProgressHUD showInfoWithStatus:@"未填写开户行"];
                          return ;
                      }
                      if (weakSelf.inforModel.province_area.length == 0) {
                            [SVProgressHUD showInfoWithStatus:@"未填写开户省市"];
                          return ;
                      }
                      LKBankListViewController *bank = [[LKBankListViewController alloc] init];
                      bank.bankProvince = weakSelf.inforModel.province_area;
                      bank.banCity = weakSelf.inforModel.city_area;
                      bank.bankAccount = weakSelf.inforModel.bank_account;
                      bank.bankBlock = ^(NSString * _Nullable bank, NSString * _Nullable bank_num) {
                          weakSelf.inforModel.branch_account = bank;
                          weakSelf.inforModel.bank_num = bank_num;
                          [weakSelf.formview removeFromSuperview];
                          [weakSelf createFormView];
                      };
//                      bank.bankBlock = ^(NSString *bank) {
//                          weakSelf.inforModel.branch_account = bank;
//                          [weakSelf.formview removeFromSuperview];
//                          [weakSelf createFormView];
//                      };
                      [weakSelf.navigationController pushViewController:bank animated:YES];
                  })
                  .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {

                  })
                  .height(RowHeightDefault)
                  .accessoryType(UFRowAccessoryDisclosureIndicator);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .height(RowHeightDefault)
                .title(@"银行卡号")
                .name(@"银行卡号")
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.bank_account_no = value;
                })
                .value(weakSelf.inforModel.bank_account_no);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .height(RowHeightDefault)
                .title(@"预留手机号")
                .name(@"预留手机号")
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.opening_phone = value;
                })
                .value(weakSelf.inforModel.opening_phone);
            }])
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFPictureRow *pictureRow = [[LKUFPictureRow alloc] init];
                pictureRow.pictureNumbers = 2;
                pictureRow.headerTitle = @"账户结算授权书（选传，用于专属通道）";
                pictureRow.picturesArray= [[NSMutableArray alloc] initWithArray:@[self.inforModel.account_authorization_one,self.inforModel.account_authorization_two]];
                pictureRow.height = 145;
                pictureRow.uploadImageBlock = ^(NSInteger selectValue, UIImageView * _Nonnull selecteImageV) {
                    dispatch_group_notify(self->_group, dispatch_get_main_queue(), ^{
                        dispatch_semaphore_signal(self->semaphore);
                        weakSelf.pictureTapSelectIndex = 8;
                        [weakSelf showAlertChooseVc];
                    });
                };
                return pictureRow;
            })
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFOpenShopBottomButtonRow *buttonRow = [[LKUFOpenShopBottomButtonRow alloc] init];
                buttonRow.height = 250;
                buttonRow.buttonTitle = @"完成";
                buttonRow.actionBlock = ^{
                    if ([NSString isBlankString:weakSelf.inforModel.uni_positive_id_card_img]) {
                         [SVProgressHUD showInfoWithStatus:@"请选择银行卡正面照"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.uni_id_card_img]) {
                         [SVProgressHUD showInfoWithStatus:@"请选择银行卡反面照"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.account_name])  {
                         [SVProgressHUD showInfoWithStatus:@"请选择开户人"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.bank_account])  {
                         [SVProgressHUD showInfoWithStatus:@"请选择开户银行"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.branch_account])  {
                         [SVProgressHUD showInfoWithStatus:@"请选择开户支行"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.province_area])  {
                         [SVProgressHUD showInfoWithStatus:@"请选择开户省市"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.bank_account_no])  {
                         [SVProgressHUD showInfoWithStatus:@"请填写银行开户卡号"];
                         return ;
                     }
                     if ([NSString isBlankString:weakSelf.inforModel.opening_phone])  {
                         [SVProgressHUD showInfoWithStatus:@"请填写银行预留手机号"];
                         return ;
                     }
                    weakSelf.inforModel.status = @"0";
                    weakSelf.inforModel.operator_name = weakSelf.inforModel.account_name;
                    NSDictionary *param = [self.inforModel properties_aps];
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopOpenInformationEditUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                       if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    
                           [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                       for(UIViewController *controller in self.navigationController.viewControllers)
                       {
                           if([controller isKindOfClass:[LKManagerAllianceViewController class]])
                           {
                               [self.navigationController popToViewController:controller animated:YES];
                               break;
                           }
                       }
                       }else{
                           [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                       }
                        
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];
                };
                return buttonRow;
            });
        }])
        .addToSuperView(self.view);
    }];
    [self.formview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT);
        make.bottom.equalTo(self.view);
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{

    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
        LKUFPictureRow *row = [self.formview findRowInRange:UFMakeRange(0, self.pictureTapSelectIndex)];
            row.selectImageV.superview.userInteractionEnabled = NO;
        NSLog(@"选中的%ld",row.selectImageV.tag);
        row.selectImageV.image = photo;
        self.selcetedUploadImage = row.selectImageV.image;
        if (self.pictureTapSelectIndex == 1) {
                dispatch_group_enter(_group);
              dispatch_group_async(_group, dispatch_get_main_queue(), ^{
                  [SVProgressHUD showWithStatus:@"图片上传中..."];
                    [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
                
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                        row.selectImageV.superview.userInteractionEnabled = YES;
                        [SVProgressHUD dismiss];
                            NSLog(@"执行结束");
                        if ([responseObject[@"code"] isEqualToString:@"success"]) {
                            if ([NSString isBlankString:responseObject[@"data"]]) {
                                [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                                return ;
                            }
                            switch (row.selectImageV.tag - 1000) {
                                case 0:
                                {
                                    self.inforModel.positive_bank_card_img = responseObject[@"data"];
                                }
                                    break;
                                case 1:
                                {
                                    self.inforModel.bank_card_img = responseObject[@"data"];
                                }
                                    break;
                                default:
                                    break;
                            }
                            dispatch_group_leave(self->_group);
                            dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                        }else{
                      dispatch_group_leave(self->_group);
                      [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
                
                    } failure:^(NSString * _Nullable error) {
                
                    }];
            });
            
        }else{
            
                dispatch_group_enter(_group);
              dispatch_group_async(_group, dispatch_get_main_queue(), ^{
                  [SVProgressHUD showWithStatus:@"图片上传中..."];
                    [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
                
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                        row.selectImageV.superview.userInteractionEnabled = YES;
                        dispatch_group_leave(self->_group);
                        dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                            NSLog(@"执行结束");
                        [SVProgressHUD dismiss];
                        if ([responseObject[@"code"] isEqualToString:@"success"]) {
                            if ([NSString isBlankString:responseObject[@"data"]]) {
                                [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                                return ;
                            }
                            switch (row.selectImageV.tag - 1000) {
                                case 0:
                                {
                                    self.inforModel.account_authorization_one = responseObject[@"data"];
                                }
                                    break;
                                case 1:
                                {
                                    self.inforModel.account_authorization_two = responseObject[@"data"];
                                }
                                    break;
                                default:
                                    break;
                            }
                        }else{
                      dispatch_group_leave(self->_group);
                      [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
                
                    } failure:^(NSString * _Nullable error) {
                
                    }];
            });
            
        }

    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{

    LKUFPictureRow *row = [self.formview findRowInRange:UFMakeRange(0, self.pictureTapSelectIndex)];
    NSLog(@"选中的%ld",row.selectImageV.tag);
    row.selectImageV.superview.userInteractionEnabled = NO;
    row.selectImageV.image = photos[0];
    self.selcetedUploadImage = row.selectImageV.image;
    if (self.pictureTapSelectIndex == 1) {
        
            dispatch_group_enter(_group);
          dispatch_group_async(_group, dispatch_get_main_queue(), ^{
              [SVProgressHUD showWithStatus:@"图片上传中..."];
                [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
            
                } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                    
        row.selectImageV.superview.userInteractionEnabled = YES;
                        NSLog(@"执行结束");
                    [SVProgressHUD dismiss];
                    if ([responseObject[@"code"] isEqualToString:@"success"]) {
                        if ([NSString isBlankString:responseObject[@"data"]]) {
                            [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                            return ;
                        }
                        switch (row.selectImageV.tag - 1000) {
                            case 0:
                            {
                                self.inforModel.positive_bank_card_img = responseObject[@"data"];
                            }
                                break;
                            case 1:
                            {
                                self.inforModel.bank_card_img = responseObject[@"data"];
                            }
                                break;
                            default:
                                break;
                        }
                        dispatch_group_leave(self->_group);
                        dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                    }else{
                  dispatch_group_leave(self->_group);
                  [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    }
            
                } failure:^(NSString * _Nullable error) {
            
                }];
        });
        
    }else{
        
            dispatch_group_enter(_group);
          dispatch_group_async(_group, dispatch_get_main_queue(), ^{
              [SVProgressHUD showWithStatus:@"图片上传中..."];
                [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
            
                } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        row.selectImageV.superview.userInteractionEnabled = YES;
                        NSLog(@"执行结束");
                    [SVProgressHUD dismiss];
                    if ([responseObject[@"code"] isEqualToString:@"success"]) {
                        if ([NSString isBlankString:responseObject[@"data"]]) {
                            [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                            return ;
                        }
                        switch (row.selectImageV.tag - 1000) {
                            case 0:
                            {
                                self.inforModel.account_authorization_one = responseObject[@"data"];
                            }
                                break;
                            case 1:
                            {
                                self.inforModel.account_authorization_two = responseObject[@"data"];
                            }
                                break;
                            default:
                                break;
                        }
                        dispatch_group_leave(self->_group);
                        dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                    }else{
                  dispatch_group_leave(self->_group);
                  [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    }
            
                } failure:^(NSString * _Nullable error) {
            
                }];
        });
        
    }

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
